<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <style>
      #box {
        width: 100px; 
        height: 100px; 
        background: blue; 
        position: absolute;
      }
    </style>
    <title>4-面向过程拖拽</title>
  </head>
<body>
  <div id="box"></div>
  <script type="text/javascript">
	/**
	 * 页面加载完成
	 * 原生:
	 * window.onLoad = function(){}
	 * window.addEventListener('load',function(){});
	 * Jquery:
	 * $(function(){});
	 */
	
	/**
	 * 思路：
	 * 依赖的事件:onmousedown onmousemove onmouseup
	 * 盒子的x坐标 : 鼠标在文档的x坐标 -盒子.offsetLeft
	 * 盒子的y坐标 : 鼠标在文档的y坐标 -盒子.offsetTop
	 * 移动的距离left/top 
	 * {
			left: 鼠标在文档的x坐标-鼠标在盒子的x坐标
			top:  鼠标在文档的y坐标-鼠标在盒子的y坐标
	   }
	 */
  	//获取元素对象
	var oBox = null;
	//全局变量-鼠标x,y
	var mouseX = 0;
	var mouseY = 0;
	//页面加载
	window.addEventListener('load',function(e){
		console.log('over..');
		oBox = document.querySelector('#box');
		//run方法
		oBox.onmousedown = runDrag;
	});
	//动作的初始化
	function runDrag(e){
		//兼容性写法
		e = e||window.event;
		console.log('abc...');
		//获取鼠标在盒子的坐标
		mouseX = e.pageX - oBox.offsetLeft;
		mouseY = e.pageY - oBox.offsetTop;
		//移动
		document.onmousemove = moveDiv;
		//抬起
		document.onmouseup = upDiv;
	}
	
	//移动
	function moveDiv(e){
		e = e|| window.event;
		console.log('move...');
		//改变left和top值
		oBox.style.left = e.pageX - mouseX+'px';
		oBox.style.top = e.pageY - mouseY+'px';
	}
	//抬起
	function upDiv(){
		console.log('up...');
		//把onmousemove和onmouseup方法置空
		document.onmousemove = null;
		document.onmouseup = null;
	}
  </script>
</body>
</html>
